import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateCategoryDto } from './dto/create-category.dto';
import { UpdateCategoryDto } from './dto/update-category.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Category } from './entities/category.entity';

@Injectable()
export class CategoriesService {
  constructor(
    @InjectRepository(Category)
    private readonly categoryRepository: Repository<Category>,
  ) {}

  async create(createCategoryDto: CreateCategoryDto) {
    const { name } = createCategoryDto;
    const oldCategory = await this.categoryRepository.findOne({
      where: { name },
    });
    if (oldCategory) {
      throw new HttpException('该分类已存在', HttpStatus.BAD_REQUEST);
    }
    const category = this.categoryRepository.create(createCategoryDto);
    return await this.categoryRepository.save(category);
  }

  async findAll() {
    return await this.categoryRepository.find();
  }

  async findOne(id: number) {
    return await this.categoryRepository.findOneBy({ id: id });
  }

  async update(id: number, updateCategoryDto: UpdateCategoryDto) {
    const existCategory = await this.categoryRepository.findOneBy({
      id: id,
    });
    if (!existCategory) {
      throw new HttpException(`id为${id}的文章不存在`, HttpStatus.FORBIDDEN);
    }
    const categoryToUpdate = this.categoryRepository.merge(
      existCategory,
      updateCategoryDto,
    );
    return await this.categoryRepository.save(categoryToUpdate);
  }

  async remove(id: number) {
    const existCategory = await this.categoryRepository.findOneBy({
      id: id,
    });
    if (!existCategory) {
      throw new HttpException(`id为${id}的文章不存在`, HttpStatus.FORBIDDEN);
    }
    return await this.categoryRepository.remove(existCategory);
  }

  async findById(id: number) {
    return await this.categoryRepository.findOneBy({ id: id });
  }
}
